package org.jeecg.modules.service;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.modules.doctor.entity.DoctorWxUserinfoRelation;
import org.jeecg.common.modules.doctor.service.IDoctorWxUserinfoRelationService;
import org.jeecg.common.modules.im.ImService;
import org.jeecg.common.modules.inquiry.entity.InquiryInfo;
import org.jeecg.common.modules.inquiry.service.IInquiryInfoService;
import org.jeecg.common.modules.patient.entity.Patient;
import org.jeecg.common.modules.patient.service.IPatientService;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.util.enums.SexEnum;
import org.jeecg.common.util.enums.centent.CustomMsgType;
import org.jeecg.common.util.result.Result;
import org.jeecg.common.util.result.ResultMapper;
import org.jeecg.common.util.tencent.ext.CustomExt;
import org.jeecg.modules.config.CustomProperties;
import org.jeecg.modules.vo.request.InquiryRequestVo;
import org.jeecg.modules.vo.respone.InquiryResponseVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

import static org.jeecg.common.util.constants.H5Constants.OVER_INQUIRY_TEMPLATE;

/**
 * @author guoyh
 * @ClassName ApiInquiryService
 * @Description
 * @since 2020/9/4 00:10
 **/
@Service
@Slf4j
public class ApiInquiryService {

    @Resource
    private IInquiryInfoService inquiryInfoService;
    @Resource
    private IDoctorWxUserinfoRelationService doctorWxUserinfoRelationService;
    @Resource
    private ImService imService;
    @Resource
    private IWxUserinfoService wxUserinfoService;
    @Resource
    private IPatientService patientService;
    @Resource
    private CustomProperties customProperties;


    public Result<InquiryResponseVo> saveInquiry(InquiryRequestVo inquiry,String openid){
        InquiryInfo info = new InquiryInfo();
        info.setCreateTime(new Date());
        info.setContent(inquiry.getContent());
        info.setDoctorId(inquiry.getDoctorId());
        info.setInquiryId(inquiry.getInquiryId());
        info.setPatientId(inquiry.getPatientId());
        inquiryInfoService.save(info);
        InquiryResponseVo vo =new InquiryResponseVo();
        vo.setId(info.getId());
        try {
            DoctorWxUserinfoRelation relation = doctorWxUserinfoRelationService.getByDoctorAndOpenid(inquiry.getDoctorId(),openid);
            WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(openid);
            Patient patient =  patientService.getById(inquiry.getPatientId());
            if (Objects.nonNull(relation)){
                String groupId = relation.getImGroupId();
                imService.sendCustomMsg(groupId,wxUserinfo.getId(),buildCustomExt(groupId,patient,inquiry.getChiefComplaint(),info.getId()));
            }
        } catch (Exception e) {
            log.error("发送问诊单自定义消息异常,{}",info.getId(),e);
        }
        return ResultMapper.<InquiryResponseVo>ok().setData(vo);
    }

    private CustomExt buildCustomExt( String roomId, Patient patient,String content,String id){
        CustomExt customExt = new CustomExt();
        customExt.setType(CustomMsgType.INQUIRY.getCode());
        customExt.setRoomId(roomId);
        customExt.setTitle("问诊单（已填）");
        customExt.setContent(Lists.newArrayList(buildPatientInfo(patient),"主诉："+content));
        customExt.setEnterUrl(String.format(OVER_INQUIRY_TEMPLATE, customProperties.getH5Domain(),id));
        customExt.setEnterText("查看详情");
        return customExt;
    }

    private String buildPatientInfo(Patient patient){
        StringBuffer sb = new StringBuffer();
        sb.append("患者：");
        sb.append(patient.getName());
        if (Objects.nonNull(patient.getSex())){
            SexEnum sexEnum = SexEnum.getInstance(patient.getSex());
            if (!Objects.equals(sexEnum,SexEnum.UNKNOWN)){
                sb.append("，"+sexEnum.getDesc());
            }
        }
        Integer age = calcAge(patient.getBirthday());
        if (Objects.nonNull(age)){
            sb.append("，"+age+"岁");
        }
        return sb.toString();
    }

    private Integer calcAge(Date birthday){
        if (Objects.isNull(birthday)){
            return null;
        }
        LocalDateTime localDateTime = DateUtil.toLocalDateTime(birthday);
        LocalDateTime now = LocalDateTime.now();
        return now.getYear() - localDateTime.getYear();
    }
}
